package com.madou.dbtool.redis.utils;

import java.io.ByteArrayOutputStream;

/**
 * 把bytes转成16进制或十进制
 */
public class BytesToStringUtil {

    /**
     * 把字节数组转成字符串
     * @param bytes
     * @return
     */
    public static String byte2Hex(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        boolean isHex = false;
        for (int i = 0; i < bytes.length; i++) {
            byte aByte = bytes[i];
            if(aByte>122||aByte<48){
                isHex = true;
                stringBuffer.append("\\x");
                temp = Integer.toHexString(bytes[i] & 0xFF);
                if (temp.length() == 1) {
                    // 1得到一位的进行补0操作
                    stringBuffer.append("0");
                }
                stringBuffer.append(temp);
            }else{
                stringBuffer.append((char)aByte);
            }
        }
//        if(isHex){
//            return "\""+stringBuffer.toString()+"\"";
//        }
        return stringBuffer.toString();
    }

    /**
     * 把字节数组转成字符串
     * @return
     */
    public static byte[] string2Byte(String string) {
        ByteArrayOutputStream out =  new ByteArrayOutputStream();
        char[] chars = string.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char aChar = chars[i];
            if('\\'==aChar){
                char type = chars[++i];
                int radix = 10;
                if('x'==type){
                    radix = 16;
                }else{
                    continue;
                }
                String data = ""+chars[++i]+ chars[++i];
                byte byteC = (byte) (0xff&Integer.parseInt(data,radix));
                out.write(byteC);
            }else{
                out.write(aChar);
            }
        }
        return out.toByteArray();
    }

}
